import { useEffect, useState } from "react";
import PubSub from "pubsub-js";
import axios from "axios";

import "./index.css";

export default function UserList() {
  const [userList, setUserList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [hasSearch, setHasSearch] = useState(false);

  useEffect(() => {
    // 订阅消息
    PubSub.subscribe("searchUserList", async (message, keyword) => {
      setHasSearch(true);
      setLoading(true);
      const result = await axios.get(
        "https://api.github.com/search/users?q=" + keyword
      );
      setUserList(
        result.data.items.map((item) => {
          return {
            id: item.id,
            avatar_url: item.avatar_url,
            login: item.login,
            html_url: item.html_url,
          };
        })
      );
      setLoading(false);
    });
    return () => {
      PubSub.unsubscribe("searchUserList");
    };
  }, [userList]);

  if (!hasSearch) {
    return <h1>输入用户名搜索</h1>;
  }

  if (loading) {
    return <h1>loading...</h1>;
  }

  if (userList.length) {
    return (
      <div class="row">
        {userList.map((user) => {
          return (
            <div class="card" key={user.id}>
              <a href={user.html_url} target="_blank" rel="noreferrer">
                <img
                  src={user.avatar_url}
                  alt={user.login}
                  style={{ width: 100 }}
                />
              </a>
              <p class="card-text">{user.login}</p>
            </div>
          );
        })}
      </div>
    );
  }

  return <h1>暂无此用户数据</h1>;
}
